package com.ictology.mei;

import android.support.v7.app.ActionBar;
import android.os.ParcelFileDescriptor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.graphics.pdf.PdfRenderer;
import android.graphics.pdf.PdfRenderer.*;
import android.graphics.Bitmap;
import java.io.IOException;
import java.net.MalformedURLException;
import java.io.*;

public class EI_book extends AppCompatActivity {

    ImageView pdfImageView ;

    private String name;
    private String pdfName;
    private final int pageCount = 5;
    Bitmap[] pdfPagesBitmaps = new Bitmap[pageCount];
    private int curIndex = 0;
    private int index = 0;
    int height = 3508;
    int width = 2480;
    private GestureDetector mGestureDetector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ei_book);
        pdfImageView = (ImageView) this.findViewById(R.id.ei_book_pdf_imageView);

        Intent pushViewIntent = this.getIntent();
        name = pushViewIntent.getStringExtra("name");
        pdfName = pushViewIntent.getStringExtra("pdf");

        intPage();

        mGestureDetector = new GestureDetector(this,new GestureListenerImpl());

        pdfImageView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent event) {
                return mGestureDetector.onTouchEvent(event);
            }
        });




        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getSupportActionBar().setCustomView(R.layout.actionbar);
        TextView title = (TextView) this.findViewById(R.id.action_bar_title);
        title.setText(name);
    }

    public boolean onTouchEvent(MotionEvent event) {
        return mGestureDetector.onTouchEvent(event);
    }

    private class GestureListenerImpl implements GestureDetector.OnGestureListener {
        @Override
        public boolean onDown(MotionEvent e) {
            return false;
        }

        @Override
        public void onShowPress(MotionEvent e) {

        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return false;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            return false;
        }

        @Override
        public void onLongPress(MotionEvent e) {

        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                               float velocityY) {
            float x = e2.getX() - e1.getX();
            float y = e2.getY() - e1.getY();

            if (x > 0) {
//                doResult(RIGHT);
                if(curIndex > 0)
                loadPage(false);

            } else if (x < 0) {
//                doResult(LEFT);

                loadPage(true);
            }
            return true;
        }
    }



    private void loadPage(boolean next) {
        System.out.println("loadPage xx");
        if (next){
            curIndex++;
            index ++;
        }

        else{
            curIndex--;
            index --;
        }

        if ((index%pageCount == 1 && !next) ||(index%pageCount == 4 && next) || index <0){
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                try {
                    File pdfFile = createFileFrom(getAssets().open(pdfName), pdfName);
                    pdfPagesBitmaps = new Bitmap[pageCount];

                    for (int i = 0; i < pdfPagesBitmaps.length; i++) {
                        pdfPagesBitmaps[i] = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);
                    }

                    PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(pdfFile, ParcelFileDescriptor.MODE_READ_ONLY));
                    for (int i = curIndex; i < pageCount + curIndex; i++) {
                        System.out.print(i+"");
                        Page page = renderer.openPage(i);


                        // say we render for showing on the screen
                        page.render(pdfPagesBitmaps[i -curIndex], null, null, Page.RENDER_MODE_FOR_DISPLAY);
//
                        // close the page
                        page.close();

                        System.out.println("render page: " + i);
                        System.out.println(pdfPagesBitmaps[i-curIndex]);
                    }

                    index = 0;

                    // close the renderer
                    renderer.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
        }

        System.out.println(index);
        pdfImageView.setImageBitmap(pdfPagesBitmaps[index]);
        pdfImageView.invalidate();

    }

    private void intPage() {

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                try {
                    File pdfFile = createFileFrom(getAssets().open(pdfName), pdfName);

                    for (int i = 0; i < pdfPagesBitmaps.length; i++) {
                        pdfPagesBitmaps[i] = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);
                    }

                    PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(pdfFile, ParcelFileDescriptor.MODE_READ_ONLY));
                    for (int i = curIndex; i < pageCount + curIndex; i++) {
                        Page page = renderer.openPage(i);


                        // say we render for showing on the screen
                        page.render(pdfPagesBitmaps[i], null, null, Page.RENDER_MODE_FOR_DISPLAY);
//
                        // close the page
                        page.close();

                        System.out.println("render page: " + i);
                        System.out.println(pdfPagesBitmaps[i]);
                    }

                    index = 0;

                    // close the renderer
                    renderer.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }

        pdfImageView.setImageBitmap(pdfPagesBitmaps[0]);
        pdfImageView.invalidate();

    }


    private File createFileFrom(InputStream input, String fileName){
        try{
            File file = new File(getCacheDir() + "/" + fileName);
            OutputStream output = new FileOutputStream(file);
            byte buffer[] = new byte[1024];
            int length = 0;

            while((length=input.read(buffer)) > 0) {
                output.write(buffer,0,length);
            }

            output.close();
            input.close();

            return file;
        }catch (IOException e) {
            System.out.println(e);
        }

        return null;


    }

}
